//
//  ShareMethods.m
//  jhjy
//
//  Created by 罗西 on 12/15/15.
//  Copyright © 2015 King. All rights reserved.
//

#import "ShareMethods.h"
#import "QQHelper.h"
#import "WXHelper.h"
#import "WeiboHelper.h"
#import "TencentAppMacro.h"
#import "SDWebImagePrefetcher.h"
#import "FrameHeader.h"
#import "AppDelegate.h"
#import "ColorHeader.h"
#import "WeiboUser.h"
#import "WXApi_.h"
#import "THud.h"
#import "payRequsestHandler.h"

@interface ShareMethods() <QQDelegate,WXApiDelegate,WEIBODelegate>

@property (nonatomic, strong) NSArray *permissions; // 需要用户授权的API

@property (nonatomic,strong) NSString *AccessToken;
@property (nonatomic,strong) NSString *OpenID;
@property (strong, nonatomic) NSString *access_token;
@property (strong, nonatomic) NSString *openid;

@property (nonatomic,strong) UIView *pickViewBgView;

@end

@implementation ShareMethods 


+ (instancetype)shareInstance {
    
    static dispatch_once_t once;
    static ShareMethods *instance = nil;
    dispatch_once(&once, ^{
        instance = [[self alloc] init];
    });
    
    return instance;
}

+ (instancetype)manager
{
    static id manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[ShareMethods alloc] init];
    });
    return manager;
}

- (void)shareNews {
    
    NSString *url = APP_URL; // 要跳转的url
    NSString *imgURL = IMAGE_URL; // 预览图的url
    
    [[QQHelper shareInstance] shareTitle:TITLE text:DESCRIPTION imgData:nil imgURL:imgURL description:DESCRIPTION url:url flashURL:nil type:QQShareTypeNews QZone:NO];
    
}

- (void)shareQzone {
    
    NSString *url = APP_URL; // 要跳转的url
    NSString *imgURL = IMAGE_URL; // 预览图的url
    
    [[QQHelper shareInstance] shareTitle:TITLE text:DESCRIPTION imgData:nil imgURL:imgURL description:DESCRIPTION url:url flashURL:nil type:QQShareTypeNews QZone:YES];
    
}

- (void)shareLinkToWX {
    
    NSString *imageURL = IMAGE_URL;
    [[SDWebImagePrefetcher sharedImagePrefetcher] prefetchURLs:[NSArray arrayWithObjects:[NSURL URLWithString:imageURL], nil]];
    [[WXHelper shareInstance] shareTitle:TITLE text:nil thumbImage:imageURL imageData:nil imageURL:nil desc:DESCRIPTION webPageURL:APP_URL mediaURL:nil audioDataURL:nil scene:WXSceneSession type:WXShareTypeLink];
}

- (void)shareLinkToWXTimeLine {
    
    NSString *imageURL = IMAGE_URL;
    [[SDWebImagePrefetcher sharedImagePrefetcher] prefetchURLs:[NSArray arrayWithObjects:[NSURL URLWithString:imageURL], nil]];
    [[WXHelper shareInstance] shareTitle:TITLE text:nil thumbImage:imageURL imageData:nil imageURL:nil desc:DESCRIPTION webPageURL:APP_URL mediaURL:nil audioDataURL:nil scene:WXSceneTimeline type:WXShareTypeLink];
}


- (void)shareLinkToWeibo{
    [[WeiboHelper shareInstance]shareTitle:TITLE localImage:nil remoteImage:IMAGE_URL];
}

- (void)loginByQQ {
    
    // permissions列表可以参考：http://wiki.connect.qq.com/api%E5%88%97%E8%A1%A8
    _permissions = [NSArray arrayWithObjects:kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                    kOPEN_PERMISSION_GET_USER_INFO,
                    nil];
    [[QQHelper shareInstance] setDelegate:self];
    [[[QQHelper shareInstance] tencentOAuth] authorize:self.permissions  inSafari:NO];
}

- (void)loginByWx:(UIViewController *)viewController{
    SendAuthReq *req =[[SendAuthReq alloc ] init];
    req.scope = @"snsapi_userinfo"; // 此处不能随意改
    req.state = @"123"; // 这个貌似没影响
    
    //[WXApi sendAuthReq:req viewController:nil delegate:self];
    [WXApi sendReq:req];
    //[WXApi sendAuthReq:req viewController:viewController delegate:self];
}

+ (BOOL)handleOpenURL:(NSURL *)url
{
    if ([[NSString stringWithFormat:@"%@",url]rangeOfString:@"UPPayDemo"].location != NSNotFound) {
        [[ShareMethods shareInstance]UUpayHandle:[NSString stringWithFormat:@"%@",url]];
    }
    return [WXApi handleOpenURL:url delegate:[ShareMethods manager]];
}

-(void)UUpayHandle:(NSString *)url{
    BOOL state;
    if ([url rangeOfString:@"success"].location != NSNotFound) {
        state = YES;
    }else{
        state = NO;
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(UPPayBack:)]) {
        [self.delegate UPPayBack:state];
    }
}


#pragma mark - QQDelegate
- (void)qqLoginSuccessful:(TencentOAuth *)tencentOAuth {
    
    NSLog(@"登录成功");
    
    if (tencentOAuth.accessToken && tencentOAuth.accessToken.length != 0) {
        // 保存AccessToken/OpenID/过期时间
        [tencentOAuth getUserInfo];
        
        NSLog(@"tencentOAuthAccessToken %@ %@", tencentOAuth.accessToken,tencentOAuth.openId);
        _AccessToken = tencentOAuth.accessToken;
        _OpenID = tencentOAuth.openId;
    }
    else {
        NSLog(@"获取accessToken失败");
    }
}

- (void)qqLoginUnsuccessful:(BOOL)cancelled {
    
    if (cancelled) {
        NSLog(@"用户取消登录");
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(ThirdPartyLoginDelegate:LoginState:PInfo:OpenID:)]) {
            [self.delegate ThirdPartyLoginDelegate:QQ LoginState:LoginUserCancel PInfo:nil OpenID:_OpenID];
        }
    }
    else {
        NSLog(@"登录失败");
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(ThirdPartyLoginDelegate:LoginState:PInfo:OpenID:)]) {
            [self.delegate ThirdPartyLoginDelegate:QQ LoginState:LoginFailure PInfo:nil OpenID:_OpenID];
        }
    }
}

- (void)qqLoginNotNetwork {
    
    NSLog(@"没网络");
    if (self.delegate && [self.delegate respondsToSelector:@selector(ThirdPartyLoginDelegate:LoginState:PInfo:OpenID:)]) {
        [self.delegate ThirdPartyLoginDelegate:QQ LoginState:LoginNotNetwork PInfo:nil OpenID:_OpenID];
    }
}

- (void)getUserInfo:(APIResponse *)userInfoResponse {
    
    // 获取用户信息
    NSLog(@"userInfoResponse %@", userInfoResponse.jsonResponse);
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(ThirdPartyLoginDelegate:LoginState:PInfo:OpenID:)]) {
        [self.delegate ThirdPartyLoginDelegate:QQ LoginState:LoginSuccessful PInfo:userInfoResponse.jsonResponse OpenID:_OpenID];
    }
}

-(void)loginByWeiBo{
    [[WeiboHelper shareInstance]SSOLogin];
    [[WeiboHelper shareInstance]setDelegate:self];
}

//- (void)didReceiveWeiboResponse:(WBBaseResponse *)response {
//    
//    NSLog(@"response weibo shaare %@", response.userInfo);
//    //_accessToken = [response.userInfo objectForKey:@"access_token"];
//}

-(void)WeiboResponse:(WBBaseResponse *)response{
    NSLog(@"response weibo shaare %@", response.userInfo);
    if ([response isKindOfClass:WBAuthorizeResponse.class]) {
        if (response.statusCode == WeiboSDKResponseStatusCodeSuccess) {
            
            [WBHttpRequest requestForUserProfile:[(WBAuthorizeResponse *)response userID]
                                 withAccessToken:[(WBAuthorizeResponse *)response accessToken]
                              andOtherProperties:nil
                                           queue:nil
                           withCompletionHandler:^(WBHttpRequest *httpRequest, id result, NSError *error) {
                               if (!error) {
                                   //[weakself getUserInfo:result];
                                   NSLog(@"weibo result:%@",result);
                                   WeiboUser *userInfo = result;
                                   [self.delegate ThirdPartyLoginDelegate:WEIBO LoginState:LoginSuccessful PInfo:@{@"userID":userInfo.userID,@"screenName":userInfo.screenName,@"profileImageUrl":userInfo.profileImageUrl,} OpenID:nil];
                               }
                               
                           }];
        } else if (response.statusCode == WeiboSDKResponseStatusCodeUserCancel) {
            [self.delegate ThirdPartyLoginDelegate:WEIBO LoginState:LoginUserCancel PInfo:nil OpenID:nil];
            
        } else {//if (response.statusCode == WeiboSDKResponseStatusCodeAuthDeny) {
            [self.delegate ThirdPartyLoginDelegate:WEIBO LoginState:LoginFailure PInfo:nil OpenID:nil];
        }
    }
}

/**
 * onReq微信终端向第三方程序发起请求，要求第三方程序响应。第三方程序响应完后必须调用
 * sendRsp返回。在调用sendRsp返回时，会切回到微信终端程序界面。
 */
- (void)onReq:(BaseReq *)req {
    
}

/**
 *  如果第三方程序向微信发送了sendReq的请求，那么onResp会被回调。sendReq请求调用后，
 *  会切到微信终端程序界面。
 */
- (void)onResp:(BaseResp *)resp {
    
//    NSLog(@"aresp:%@",resp);
//    if (![resp isKindOfClass:[SendAuthResp class]]) {
//        return;
//    }
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        //NSString *strTitle = [NSString stringWithFormat:@"支付结果"];
        NSString *strMsg = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
        
        switch (resp.errCode) {
            case WXSuccess:{
                strMsg = @"支付结果：成功！";
                NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
                
                [[ShareMethods shareInstance].delegate WXpayBack:true];
                break;
            }
            default:{
                strMsg = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                NSLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
                
                [[ShareMethods shareInstance].delegate WXpayBack:false];
                break;
            }
        }
    }else if([resp isKindOfClass:[SendAuthResp class]]){
        SendAuthResp *aresp = (SendAuthResp *)resp;
        if (aresp.errCode == 0) { // 用户同意
            //        NSLog(@"errCode = %d", aresp.errCode);
            //        NSLog(@"code = %@", aresp.code);
            
            // 获取access_token
            //      格式：https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
            NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code", kWXAppKey, kWXSecrtKey, aresp.code];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSURL *zoneUrl = [NSURL URLWithString:url];
                NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
                NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (data) {
                        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                        _openid = [dic objectForKey:@"openid"]; // 初始化
                        _access_token = [dic objectForKey:@"access_token"];
                        //                    NSLog(@"openid = %@", _openid);
                        //                    NSLog(@"access = %@", [dic objectForKey:@"access_token"]);
                        NSLog(@"dic = %@", dic);
                        [self getUserInfo]; // 获取用户信息
                    }
                });
            });
        } else if (aresp.errCode == -2) {
            NSLog(@"用户取消登录");
            [self.delegate ThirdPartyLoginDelegate:WEIXIN LoginState:LoginUserCancel PInfo:nil OpenID:_OpenID];
        } else if (aresp.errCode == -4) {
            NSLog(@"用户拒绝登录");
            [self.delegate ThirdPartyLoginDelegate:WEIXIN LoginState:LoginUserRefuse PInfo:nil OpenID:_OpenID];
        } else {
            NSLog(@"errCode = %d", aresp.errCode);
            NSLog(@"code = %@", aresp.code);
        }

    }
}

// 获取用户信息
- (void)getUserInfo {
    NSString *url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@", self.access_token, self.openid];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSLog(@"openid = %@", [dic objectForKey:@"openid"]);
                NSLog(@"nickname = %@", [dic objectForKey:@"nickname"]);
                NSLog(@"sex = %@", [dic objectForKey:@"sex"]);
                NSLog(@"country = %@", [dic objectForKey:@"country"]);
                NSLog(@"province = %@", [dic objectForKey:@"province"]);
                NSLog(@"city = %@", [dic objectForKey:@"city"]);
                NSLog(@"headimgurl = %@", [dic objectForKey:@"headimgurl"]);
                NSLog(@"unionid = %@", [dic objectForKey:@"unionid"]);
                NSLog(@"privilege = %@", [dic objectForKey:@"privilege"]);
                
                [[ShareMethods shareInstance].delegate ThirdPartyLoginDelegate:WEIXIN LoginState:LoginSuccessful PInfo:dic OpenID:[dic objectForKey:@"openid"]];
                
//                AppDelegate *appdelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//                appdelegate.headimgurl = [dic objectForKey:@"headimgurl"]; // 传递头像地址
//                appdelegate.nickname = [dic objectForKey:@"nickname"]; // 传递昵称
//                NSLog(@"appdelegate.headimgurl == %@", [dic objectForKey:@"headimgurl"]); // 测试
//                NSLog(@"appdelegate.nickname == %@", [dic objectForKey:@"nickname"]);
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"Note" object:nil]; // 发送通知
            }
        });
    });
}

#define ICON_SIZE_WIDTH 50
#define INSERT 30
-(void)loadShareMenu{
    _pickViewBgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _pickViewBgView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    [[AppDelegate sharedDelegate].window addSubview:_pickViewBgView];
    
    UIView *pickBgView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-144, SCREEN_WIDTH, 144)];
    pickBgView.backgroundColor = [UIColor whiteColor];
    [_pickViewBgView addSubview:pickBgView];
    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*1/10-ICON_SIZE_WIDTH/2, INSERT, ICON_SIZE_WIDTH, ICON_SIZE_WIDTH)];
    [btn setImage:[UIImage imageNamed:@"share_qq_logo"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(shareEvent:) forControlEvents:UIControlEventTouchUpInside];
    btn.imageView.contentMode = UIViewContentModeScaleAspectFill;
    [pickBgView addSubview:btn];
    btn.tag = 1;
    
    UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*3/10-ICON_SIZE_WIDTH/2, INSERT, ICON_SIZE_WIDTH, ICON_SIZE_WIDTH)];
    [btn2 setImage:[UIImage imageNamed:@"qzone"] forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(shareEvent:) forControlEvents:UIControlEventTouchUpInside];
    //btn2.imageView.contentMode = UIViewContentModeScaleAspectFill;
    [pickBgView addSubview:btn2];
    btn2.tag = 2;
    
    UIButton *btn3 = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*5/10-ICON_SIZE_WIDTH/2, INSERT, ICON_SIZE_WIDTH, ICON_SIZE_WIDTH)];
    [btn3 setImage:[UIImage imageNamed:@"share_wechat_logo"] forState:UIControlStateNormal];
    [btn3 addTarget:self action:@selector(shareEvent:) forControlEvents:UIControlEventTouchUpInside];
    btn3.imageView.contentMode = UIViewContentModeScaleAspectFill;
    [pickBgView addSubview:btn3];
    btn3.tag = 3;
    
    UIButton *btn4 = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*7/10-ICON_SIZE_WIDTH/2, INSERT, ICON_SIZE_WIDTH, ICON_SIZE_WIDTH)];
    [btn4 setImage:[UIImage imageNamed:@"share_friendscircle_logo"] forState:UIControlStateNormal];
    [btn4 addTarget:self action:@selector(shareEvent:) forControlEvents:UIControlEventTouchUpInside];
    btn4.imageView.contentMode = UIViewContentModeScaleAspectFill;
    [pickBgView addSubview:btn4];
    btn4.tag = 4;
    
    UIButton *btn5 = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*9/10-ICON_SIZE_WIDTH/2, INSERT, ICON_SIZE_WIDTH, ICON_SIZE_WIDTH)];
    [btn5 setImage:[UIImage imageNamed:@"share_weibo_logo"] forState:UIControlStateNormal];
    [btn5 addTarget:self action:@selector(shareEvent:) forControlEvents:UIControlEventTouchUpInside];
    btn5.imageView.contentMode = UIViewContentModeScaleAspectFill;
    [pickBgView addSubview:btn5];
    btn5.tag = 5;
    
    UIView *sepView = [[UIView alloc]initWithFrame:CGRectMake(0, 99.5, SCREEN_WIDTH, 0.5)];
    sepView.backgroundColor = [UIColor lightGrayColor];
    [pickBgView addSubview:sepView];
    
    UIButton *cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 100, SCREEN_WIDTH, 44)];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:SIGNINBTN_COLOR forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(shareMenuCancel) forControlEvents:UIControlEventTouchUpInside];
    [pickBgView addSubview:cancelBtn];
    
//    UILabel *data = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-60, 14, 120, 16)];
//    data.text = @"选择时间";
//    data.textAlignment = NSTextAlignmentCenter;
//    data.textColor = [UIColor blackColor];
//    [pickBgView addSubview:data];
    

    
    
    //隐藏键盘
    [[AppDelegate sharedDelegate].window endEditing:YES];
}

-(void)shareEvent:(UIButton *)sender{
     [_pickViewBgView removeFromSuperview];
    switch (sender.tag) {
        case 1:
            [self shareNews];
            break;
        case 2:
            [self shareQzone];
            break;
        case 3:
            [self shareLinkToWX];
            break;
        case 4:
            [self shareLinkToWXTimeLine];
            break;
        case 5:
            [self shareLinkToWeibo];
            break;
            
        default:
            break;
    }
}

-(void)shareMenuCancel{
    [_pickViewBgView removeFromSuperview];
}

- (BOOL)isWXAppInstalled
{
    // 1.判断是否安装微信
    if (![WXApi isWXAppInstalled]) {
        [[THud sharedInstance]showText:@"您尚未安装\"微信App\",请先安装后再返回支付" Delay:2.0];
        return NO;
    }
    // 2.判断微信的版本是否支持最新Api
    if (![WXApi isWXAppSupportApi]) {
        [[THud sharedInstance]showText:@"您微信当前版本不支持此功能,请先升级微信应用" Delay:2.0];
        return NO;
    }
    return YES;
}


- (void)sendPay
{
    //从服务器获取支付参数，服务端自定义处理逻辑和格式
    //订单标题
    NSString *ORDER_NAME    = @"Ios服务器端签名支付 测试";
    //订单金额，单位（元）
    NSString *ORDER_PRICE   = @"0.01";
    
    //根据服务器端编码确定是否转码
    NSStringEncoding enc;
    //if UTF8编码
    //enc = NSUTF8StringEncoding;
    //if GBK编码
    enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSString *urlString = [NSString stringWithFormat:@"%@?plat=ios&order_no=%@&product_name=%@&order_price=%@",
                           SP_URL,
                           [[NSString stringWithFormat:@"%ld",time(0)] stringByAddingPercentEscapesUsingEncoding:enc],
                           [ORDER_NAME stringByAddingPercentEscapesUsingEncoding:enc],
                           ORDER_PRICE];
    
    //解析服务端返回json数据
    NSError *error;
    //加载一个NSURL对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    //将请求的url数据放到NSData对象中
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if ( response != nil) {
        NSMutableDictionary *dict = NULL;
        //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
        dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
        
        NSLog(@"url:%@",urlString);
        if(dict != nil){
            NSMutableString *retcode = [dict objectForKey:@"retcode"];
            if (retcode.intValue == 0){
                NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
                
                //调起微信支付
                PayReq* req             = [[PayReq alloc] init];
                req.openID              = [dict objectForKey:@"appid"];
                req.partnerId           = [dict objectForKey:@"partnerid"];
                req.prepayId            = [dict objectForKey:@"prepayid"];
                req.nonceStr            = [dict objectForKey:@"noncestr"];
                req.timeStamp           = stamp.intValue;
                req.package             = [dict objectForKey:@"package"];
                req.sign                = [dict objectForKey:@"sign"];
                [WXApi sendReq:req];
                //日志输出
                NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",req.openID,req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
            }else{
                [[THud sharedInstance]showText:[NSString stringWithFormat:@"提示信息%@",[dict objectForKey:@"retmsg"]]];
            }
        }else{
            [[THud sharedInstance]showText:[NSString stringWithFormat:@"服务器返回错误%@",[dict objectForKey:@"retmsg"]]];
            
        }
    }else{
        [[THud sharedInstance]showText:[NSString stringWithFormat:@"服务器返回错误"]];
    }
}

- (void)sendPay_demo:(NSString *)orderno pay:(NSString *)payMoney body:(NSString *)body
{
    [[THud sharedInstance]showProgress];
    //{{{
    //本实例只是演示签名过程， 请将该过程在商户服务器上实现
    
    //创建支付签名对象
    payRequsestHandler *req = [[payRequsestHandler alloc] init];
    //初始化支付签名对象
    [req init:APP_ID mch_id:MCH_ID];
    //设置密钥
    [req setKey:PARTNER_ID];
    
    //}}}
    
    //获取到实际调起微信支付的参数后，在app端调起支付
    NSMutableDictionary *dict = [req sendPay_demo:orderno pay:payMoney body:body];
    
    if(dict == nil){
        //错误提示
        NSString *debug = [req getDebugifo];
        
        [[THud sharedInstance]showText:[NSString stringWithFormat:@"%@",debug]];
        
        NSLog(@"%@\n\n",debug);
    }else{
        NSLog(@"%@\n\n",[req getDebugifo]);
        //[self alert:@"确认" msg:@"下单成功，点击OK后调起支付！"];
        
        NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
        
        //调起微信支付
        PayReq* req             = [[PayReq alloc] init];
        req.openID              = [dict objectForKey:@"appid"];
        req.partnerId           = [dict objectForKey:@"partnerid"];
        req.prepayId            = [dict objectForKey:@"prepayid"];
        req.nonceStr            = [dict objectForKey:@"noncestr"];
        req.timeStamp           = stamp.intValue;
        req.package             = [dict objectForKey:@"package"];
        req.sign                = [dict objectForKey:@"sign"];
        
        [WXApi sendReq:req];
        //[[THud sharedInstance]hideHud];
    }
}

- (void)sendPay_demo2:(NSString *)orderno pay:(NSString *)payMoney body:(NSString *)body
{
    [[THud sharedInstance]showProgress];
    //{{{
    //本实例只是演示签名过程， 请将该过程在商户服务器上实现
    
    //创建支付签名对象
    payRequsestHandler *req = [[payRequsestHandler alloc] init];
    //初始化支付签名对象
    [req init:APP_ID mch_id:MCH_ID];
    //设置密钥
    [req setKey:PARTNER_ID];
    
    //}}}
    
    //获取到实际调起微信支付的参数后，在app端调起支付
    NSMutableDictionary *dict = [req sendPay_demo2:orderno pay:payMoney body:body];
    
    if(dict == nil){
        //错误提示
        NSString *debug = [req getDebugifo];
        
        [[THud sharedInstance]showText:[NSString stringWithFormat:@"%@",debug]];
        
        NSLog(@"%@\n\n",debug);
    }else{
        NSLog(@"%@\n\n",[req getDebugifo]);
        //[self alert:@"确认" msg:@"下单成功，点击OK后调起支付！"];
        
        NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
        
        //调起微信支付
        PayReq* req             = [[PayReq alloc] init];
        req.openID              = [dict objectForKey:@"appid"];
        req.partnerId           = [dict objectForKey:@"partnerid"];
        req.prepayId            = [dict objectForKey:@"prepayid"];
        req.nonceStr            = [dict objectForKey:@"noncestr"];
        req.timeStamp           = stamp.intValue;
        req.package             = [dict objectForKey:@"package"];
        req.sign                = [dict objectForKey:@"sign"];
        
        [WXApi sendReq:req];
        //[[THud sharedInstance]hideHud];
    }
}

@end
